package api

import (
	"crypto/md5"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"sieve_admin_server_userpass/pkg/im3/app"
	"sort"
	"strconv"
	"strings"
	"time"
)

func genSig(data map[string]string) string {
	keys := []string{}
	for k := range data {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	s := ""
	for _, k := range keys {
		s += k + "=" + data[k]
	}
	return fmt.Sprintf("%x", md5.Sum([]byte(s+app.Secret())))
}

func reqApi(name string, data map[string]string) ([]byte, error) {
	data["appid"] = strconv.Itoa(app.AppId())
	data["t"] = strconv.FormatInt(time.Now().Unix(), 10)
	data["sig"] = genSig(data)
	values := make(url.Values)
	for k, v := range data {
		values.Add(k, v)
	}
post:
	res, err := http.PostForm("https://"+app.Server()+"/app/api/"+name, values)
	if err != nil {
		if strings.Contains(err.Error(), "timeout") {
			goto post
		}
		return nil, err
	}
	defer res.Body.Close()
	b, err := io.ReadAll(res.Body)
	if err == nil && res.StatusCode != http.StatusOK {
		return nil, errors.New(string(b))
	}
	return b, err
}
